/**
 * 资产类别占比
 */
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { Row, Col, Spin, Tooltip, Radio } from 'antd';
import { SecondHeaderC, TableC, IconC } from '../../../../../comps';
import ChartPie from './chartPie';
import accounting from 'accounting';
import _ from 'lodash';
import myStyle from './index.less';

class AssetTypeRatio extends PureComponent {
  constructor() {
    super();
    this.state = {
      columns: [],
      dataSource: [],
      pieData: [], // 饼图数据
      currentPage: 1,
      numInPage: 1000,
      zqfz: '0', // 证券负债 0-占比为负，1：占比为正
    };
  }

  componentDidMount() {
    const { searchData } = this.props;
    this.props.onRef(this);
    this.getData(searchData);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const { searchData } = nextProps;

    if (JSON.stringify(searchData) !== JSON.stringify(this.props.searchData)) {
      this.getData(searchData);
    }
  }

  // 获取数据
  getData = (args) => {
    const { currentPage, numInPage, zqfz } = this.state;
    this.props.dispatch({
      type: 'assetAllocationCM/queryAssetsBig',
      payload: {
        ...args,
        zqfz,
        currentPage,
        numInPage,
      },
      callback: (data) => {
        if (data && data.dataSource.length && data.columns.length) {
          const pieData = this.queryPieData(data.dataSource);
          const columnss = this.changeColumns(data.columns);
          const dataSources = this.changeDataSource(data.dataSource);
          this.setState({
            columns: columnss,
            dataSource: dataSources,
            pieData,
          });
        } else {
          this.setState({
            columns: [],
            dataSource: [],
            pieData: [],
          });
        }
      },
    });
  };

  // 获取饼图数据
  queryPieData = (dataSource) => {
    const pieData = [];
    dataSource.map((item) => {
      const { assetType, holdRatio, holdAmount } = item;
      if (assetType !== '总计') {
        pieData.push({
          name: assetType,
          value: holdRatio?.toFixed(4),
          holdAmount,
        });
      }
    });
    return pieData.sort((a, b) => {
      return b.value - a.value;
    });
  };

  // 改变表格钱数据样式
  changMoney = (data) => {
    if (data === null || data === undefined) {
      return '--';
    } else {
      return accounting.formatNumber(Number(data), 2);
    }
  };

  // 改变表格利率数据样式
  changRate = (data) => {
    if (data === null || data === undefined) {
      return '--';
    } else if (isNaN(data)) {
      return data;
    } else {
      return `${(Number(data) * 100).toFixed(2)}%`;
    }
  };

  // 优化表格数据
  changeDataSource = (dataSource) => {
    const newDataSource = _.cloneDeep(dataSource);
    const arrow = { margin: '0 0 4px 4px', width: '12px', height: '12px', display: 'inline-block' };
    newDataSource.forEach((value) => {
      if (value.holdAmountChangeFlg == 'up') {
        value.holdAmountChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cellUp}>{this.changMoney(value.holdAmountChange)}</span> <IconC type={'upRegulate'} style={arrow} />
          </div>
        );
      } else if (value.holdAmountChangeFlg == 'down') {
        value.holdAmountChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cellDown}>{this.changMoney(value.holdAmountChange)}</span> <IconC type={'downRegulate'} style={arrow} />
          </div>
        );
      } else {
        value.holdAmountChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cell}>{this.changMoney(value.holdAmountChange)}</span>
            <div style={arrow}></div>
          </div>
        );
      }
      if (value.holdRatioChangeFlg == 'up') {
        value.holdRatioChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cellUp}>{this.changRate(value.holdRatioChange)}</span> <IconC type={'upRegulate'} style={arrow} />
          </div>
        );
      } else if (value.holdRatioChangeFlg == 'down') {
        value.holdRatioChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cellDown}>{this.changRate(value.holdRatioChange)}</span> <IconC type={'downRegulate'} style={arrow} />
          </div>
        );
      } else {
        value.holdRatioChange = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span className={myStyle.cell}>{this.changRate(value.holdRatioChange)}</span>
            <div style={arrow}></div>
          </div>
        );
      }
    });
    const compare = (key) => {
      return (obj1, obj2) => {
        // 降序
        const val1 = obj1[key];
        const val2 = obj2[key];
        if (val1 < val2) {
          return 1;
        } else if (val1 > val2) {
          return -1;
        } else {
          return 0;
        }
      };
    };
    const data = newDataSource[newDataSource.length - 1];
    newDataSource.pop();
    newDataSource.sort(compare('holdRatio'));
    newDataSource.push(data);

    return newDataSource;
  };

  // 优化表格样式
  changeColumns = (columns) => {
    columns.forEach((value, index) => {
      if (value.key == 'holdRatio') {
        value.type = 'rate';
        value.width = '87px';
      }
      if (value.key == 'holdAmount') {
        value.type = 'money';
        value.width = '152px';
      }
      if (value.key == 'assetType') {
        value.width = '87px';
      }

      if (value.key == 'holdAmountChange') {
        value.title = <div style={{ textAlign: 'right' }}>{value.title}</div>;
        value.width = '167px';
      }
      if (value.key == 'holdRatioChange') {
        value.title = (
          <div style={{ textAlign: 'right' }}>
            {' '}
            <span>{value.title}</span>
            <Tooltip title={<div>该类资产期初市值占比与期末市值占比之差</div>}>
              <QuestionCircleOutlined style={{ paddingLeft: '7px' }} />
            </Tooltip>
          </div>
        );
        value.width = '120px';
      }
    });
    return columns;
  };

  // 占比切换
  chartChange = (e) => {
    sessionStorage.setItem('changeSavezqfz', e.target.value);
    this.setState(
      {
        zqfz: e.target.value,
      },
      () => {
        const { searchData } = this.props;
        this.getData(searchData);
        this.props.onChange({ zqfz: this.state.zqfz }, '4002_0');
        this.props.onChange({ zqfz: this.state.zqfz }, '4003_0');
      },
    );
  };

  render() {
    const { pieData, columns, dataSource, zqfz } = this.state;
    const { colorType } = this.props;
    return (
      <div style={{ width: '100%' }}>
        <SecondHeaderC
          title='资产类别占比'
          colorType={colorType}
          Right={
            <div className={myStyle.radioGroup}>
              <Radio.Group onChange={(e) => this.chartChange(e)} value={zqfz}>
                <Radio.Button value='0'>负债占比为负</Radio.Button>
                <Radio.Button value='1'>负债占比为正</Radio.Button>
              </Radio.Group>
            </div>
          }
        />
        <Spin spinning={this.props.loading == true}>
          <Row>
            <Col span={8} style={{ paddingRight: '10px' }}>
              <ChartPie data={pieData} height={dataSource.length ? (dataSource.length + 1) * 41 + 10 : 338} colorType={colorType} />
            </Col>
            <Col span={16} style={{ paddingLeft: '10px' }}>
              <TableC
                columns={columns}
                dataSource={dataSource}
                rowKey='assetType'
                hidePage={true}
                colorType={colorType}
                // scroll={{ x: 670 }}
              />
            </Col>
          </Row>
        </Spin>
      </div>
    );
  }
}
export default connect(({ assetAllocationCM, loading }) => ({
  assetAllocationCM,
  loading: loading.effects['assetAllocationCM/queryAssetsBig'],
}))(AssetTypeRatio);
